package sadi.client;

import java.awt.event.*;
import javax.swing.JOptionPane;
import javax.swing.*;

import java.util.*;

public class Controller 
{
	//private Model model;
	private WikiClient model;
	private GUI view;
	
	private ArrayList<ArrayList> array = null;
	
	/****************************************************************************
	 * CONSTRUCTOR
	 ****************************************************************************/
	public Controller(WikiClient model, GUI gui)
	{
		this.view = gui;
		this.model = model;
		
		/******Add Listeners to Controller********/
		view.addRegisterListener(new RegisterListener());
		view.addLoginListener(new LoginListener());
		view.addLogoutListener(new LogoutListener());
		view.addSearchListener(new SearchListener());
		view.addAddWikiListener(new AddWikiListner());
		view.addApproveWikiListener(new ApproveWikiListener());
		view.addReportedWikiListener(new ReportedWikiListener());
		view.addUpdateWelcomeListener(new UpdateWelcomeListener());
		//view.addChatListener(new ChatListener());
		view.addEditListener(new EditListener());
		view.addReportListener(new ReportListener());
		view.addDeleteListener(new DeleteListener());
		view.addDoneListener(new DoneListener());
		view.addClearListener(new ClearListener());
		view.addApproveListener(new ApproveListener());
		view.addApproveAllListener(new ApproveAllListener());
		view.addDenyListener(new DenyListener());
		view.addDeleteAllListener(new DeleteAllListener());
		view.addIgnoreListener(new IgnoreListener());
	}

	/****************************************************************************
	 * INNER CLASS FOR THE LISTENERS
	 ****************************************************************************/
	
	class NewUserListener implements ActionListener
	{

		@Override
		public void actionPerformed(ActionEvent e) {
			RegisterClient register = (RegisterClient) ((JButton)e.getSource()).getTopLevelAncestor();
			char[] passwordInput = register.getPassword1();
			char[] passwordConfirm = register.getPassword2();
			String username = register.getUsername();
			
			boolean registerCheck = true;
		
			if((username.compareTo("") )== 0)
			{
				JOptionPane.showMessageDialog(null, "Please fill in all the fiedls to register", "Error", JOptionPane.ERROR_MESSAGE );
				register.resetAllFields();
				registerCheck = false;
			}
			else if((passwordInput.toString().compareTo("") )== 0)
			{
				JOptionPane.showMessageDialog(null, "Please fill in all the fiedls to register", "Error", JOptionPane.ERROR_MESSAGE );
				register.resetAllFields();
				registerCheck = false;
			}
			else if ((passwordConfirm.toString().compareTo("") )== 0)
			{
				JOptionPane.showMessageDialog(null, "Please fill in all the fiedls to register", "Error", JOptionPane.ERROR_MESSAGE );
				register.resetAllFields();
				registerCheck = false;
			}
			
			if(registerCheck)
			{
				boolean passwordCheck = true;
				
				if(passwordInput.length != passwordConfirm.length)
				{
					JOptionPane.showMessageDialog(null, "Password and confirm password are not the same.", "Password Mismatch", JOptionPane.ERROR_MESSAGE );
					register.resetPasswordField();
					passwordCheck = false;
				}
				else
				{
					for(int i = 0; i < passwordInput.length; i++)
					{
						//if passowrd is wrong
						if(passwordInput[i] != passwordConfirm[i])
						{
							JOptionPane.showMessageDialog(null, "Password and confirm password are not the same.", "Password Mismatch", JOptionPane.ERROR_MESSAGE );
							register.resetPasswordField();
							passwordCheck = false;
							break;
						}
					}
					if(passwordCheck)
					{
						model.registerUser(username, passwordInput.toString());
						register.setVisible(false);
						register.dispose();
					}
				}
			}
			
		}
	}
	
	class ClearFormListener implements ActionListener
	{

		@Override
		public void actionPerformed(ActionEvent e) {
			RegisterClient register = (RegisterClient) ((JButton)e.getSource()).getTopLevelAncestor();
			register.resetAllFields();
			
		}
	}
	
	class CancelRegistrationListener implements ActionListener
	{

		@Override
		public void actionPerformed(ActionEvent e) {
			RegisterClient register = (RegisterClient) ((JButton)e.getSource()).getTopLevelAncestor();
		
			register.setVisible(false);
			register.dispose();
			
		}
	}
	
	//Every action performed has to revalidate the panels
	class RegisterListener implements ActionListener
	{
		public void actionPerformed(ActionEvent e)
		{
			//prompt the Register Box
			/*LoginPanel pnlLogin = new LoginPanel();
			boolean isRegister = false;
			if ((view.promptConfirm("Register", pnlLogin)) == 0)
			{
				String username = pnlLogin.getName();
				String password = pnlLogin.getPassword();
				System.out.println(username + ": " + password);
				isRegister = model.registerUser(username, password);//insert into database
				
				System.out.println("Register?" + isRegister);
				if (isRegister)//if Register successful
				{
					view.promptMsg("Yahoo! You registered successfully!", "Congratulations! You have been registered.\n" + 
							"Please log in now to enjoy Shared Wiki!", JOptionPane.PLAIN_MESSAGE);
				}
				else
					view.promptMsg("Oops!", "We can't register you at this moment. Please try again :)", JOptionPane.ERROR_MESSAGE);
                System.out.println(isRegister);
			}*/
			
			view.promptRegister(new NewUserListener(), new ClearFormListener(), new CancelRegistrationListener());
		}
	}
	
	class LoginListener implements ActionListener
	{
		public void actionPerformed(ActionEvent e)
		{
			
			//prompt the Login Box
			LoginPanel pnlLogin = new LoginPanel();
			int login = 0;
			if ((view.promptConfirm("Log In", pnlLogin)) == 0)
			{
				String username = pnlLogin.getName();
				String password = pnlLogin.getPassword();
				login = model.loginUser(username, password);//check with the server username and password
				
				if (login != -1)//if login successful
				{
					view.setIsLogin(true);
					if(model.isAdmin(login))
						view.setIsAdmin(true);
					view.setUserID(login);//set the username and userid/***************************************/
					view.setUsername(username);/************************************************/
					//refresh the panels
					view.setUserPanel();
					view.setQuickLinks();
					
					view.promptMsg("Log In Successful", "Welcome back, "  + username + "!", JOptionPane.PLAIN_MESSAGE);
					//System.out.println("User:" +  view.getUsername() + view.getUserID() + view.getIsLogin() + view.getIsAdmin());
				}
				else
					view.promptMsg("Cannot Log in", "Error Loggging in. Please try again :)", JOptionPane.ERROR_MESSAGE);
                //System.out.println(login);
			}
			/*else
				view.promptMsg("Error","We cannot log  you in... " );*/
		}
	}
	
	class LogoutListener implements ActionListener
	{
		public void actionPerformed(ActionEvent e)
		{
			
			int confirm = view.promptConfirm("Logging Out...", "Do you want to Log out?");
			if( confirm == 0);
			{
				view.setIsLogin(false);
				view.setIsAdmin(false);
				
				//refresh the panels
				view.setUserPanel();
				view.setQuickLinks();
				view.refreshContent();
			}
			
		}
	}
	
	class SearchListener implements ActionListener
	{
		public void actionPerformed(ActionEvent e)
		{
			view.setModeListView(model.searchWiki(view.getSearchKeyword()));
		}
	}
	class AddWikiListner implements ActionListener
	{
		public void actionPerformed(ActionEvent e)
		{
			//check if the user is logged in before refreshing the panel
			if(view.getIsLogin())
				view.setModeNew();
		}
	}
	class ApproveWikiListener implements ActionListener
	{
		public void actionPerformed(ActionEvent e)
		{
			ArrayList<ArrayList<String>> array = (model.getApprovalList(view.getUserID()));
			
			view.setModeListView(model.getApprovalList(view.getUserID()));
			if(array.size() > 0)
			{
				view.setContentType(GUI.LIST_APPROVE);
			}
			else
				view.setContentType(GUI.VIEW);
			
			//Check if the user is admin before refreshing the panel
			/*if (view.getIsAdmin())
			{
				//Then pass in results in arraylist -> refresh
				view.setModeListApprove(model.getApprovalList(view.getUserID()));
				System.out.println(model.getApprovalList(view.getUserID()));
			}*/
				
		}
	}
	class ReportedWikiListener implements ActionListener
	{
		public void actionPerformed(ActionEvent e)
		{
			ArrayList<ArrayList<String>> array = (model.getReportedList(view.getUserID()));
			view.setModeListView(model.getReportedList(view.getUserID()));
			
			if(array.size() > 0)
			{
				view.setContentType(GUI.LIST_REPORTED);
			}
			else
				view.setContentType(GUI.VIEW);
			
			//System.out.println("Curr WikiID: " + view.getCurrWikiID() + " Curr User: " + view.getUserID() + "CurrentType: " + view.getContentType() );
			//Check if the user is admin before refreshing the panel
			/*if (view.getIsAdmin())
			{
				//Then pass in results in arraylist
				view.setModeListReported(model.getReportedList(view.getUserID()));
				System.out.println(model.getReportedList(view.getUserID()));
			}*/
		}
	}
	class UpdateWelcomeListener implements ActionListener
	{
		public void actionPerformed(ActionEvent e)
		{
			if(view.getIsAdmin())
			{
				//Prompt admin for new msg input
				String msg = view.promptInput();
				model.setIntroduction(msg, view.getUserID());
				view.setWelcomeMsg(msg);
			}
			
		}
	}
	/*class ChatListener implements ActionListener
	{
		public void actionPerformed(ActionEvent e)
		{
			System.out.println("ChatListener");
		}
	}*/
	class EditListener implements ActionListener
	{
		public void actionPerformed(ActionEvent e)
		{
			//check if the user is login and is the current author
			if(view.getIsLogin() && view.getUserID() == view.getCurrAuthor())
			{
				view.setModeEdit();
			}
			
		}
	}
	class ReportListener implements ActionListener
	{
		public void actionPerformed(ActionEvent e)
		{
			if (view.getIsLogin())
			{
				int confirm = view.promptConfirm("You are going to report abuse...", "Are you sure you want to report this as abusive content?");
				if (confirm == 0)
				{
					boolean bool  = model.addReport(view.getCurrWikiID(), view.getUserID());
				}
			}
			
		}
	}
	class DeleteListener implements ActionListener
	{
		public void actionPerformed(ActionEvent e)
		{
			if (view.getIsLogin() && view.getIsAdmin())
			{
				int confirm = view.promptConfirm("Delete wiki", "Are you sure you want to delete this wiki?");
				if (confirm == 0)
				{
					model.deleteWiki(view.getCurrWikiID(), view.getCurrAuthor());
				}
			}
			else if (view.getIsLogin() && !view.getIsAdmin())
			{
				if(view.getCurrAuthor() == view.getUserID())
				{
					int confirm = view.promptConfirm("Delete wiki", "Are you sure you want to delete this wiki?");
					if (confirm == 0)
					{
						model.deleteWiki(view.getCurrWikiID(), view.getCurrAuthor());
					}
				}
				else
					view.promptMsg("Oops!", "You cannot delete this wiki!", JOptionPane.ERROR_MESSAGE);
			}
			view.setHighlights(model.getHighlightList());
		}
	}
	class DoneListener implements ActionListener
	{
		public void actionPerformed(ActionEvent e)
		{
			int currState = view.getContentType();
			if (currState == GUI.NEW)
			{
				String title = view.getInputTitle();
				String desc = view.getInputDesc();
				String content = view.getInputContent();
				model.addWiki(title, desc, content, view.getUserID()); 
			}
			else if (currState == GUI.EDIT)
			{
				String title = view.getInputTitle();
				String desc = view.getInputDesc();
				String content = view.getInputContent();
				model.editWiki(view.getCurrWikiID(), title, desc, content, view.getUserID()); 
			}
			else
				view.promptMsg("Woopsie~", "Some unexpected error occurs. Please try again. :)", JOptionPane.ERROR_MESSAGE);
			view.setHighlights(model.getHighlightList());
		}
		
	}
	class ClearListener implements ActionListener
	{
		public void actionPerformed(ActionEvent e)
		{
			view.clearContent();
			view.clearDesc();
			view.clearTitle();
		}
	}
	class ApproveListener implements ActionListener
	{
		public void actionPerformed(ActionEvent e)
		{
			if (view.getIsLogin() && view.getIsAdmin())
			{
				int confirm = view.promptConfirm("Approve wiki", "Are you sure you want to approve this wikis?");
				if (confirm == 0)
				{
					model.approveWiki(view.getCurrWikiID(), view.getUserID());
				
				}
			}
			
			else
				view.promptMsg("Oops!", "You have no permission to do this!", JOptionPane.ERROR_MESSAGE);
			
			view.setHighlights(model.getHighlightList());
		}
	}
	class ApproveAllListener implements ActionListener
	{
		public void actionPerformed(ActionEvent e)
		{
			if (view.getIsLogin() && view.getIsAdmin())
			{
				int confirm = view.promptConfirm("Approve wiki", "Are you sure you want to approve all the wikis?");
				if (confirm == 0)
				{
					//model.approveWiki(view.getCurrWikiID(), view.getCurrAuthor());//This one how to approve all the wikis?*********************************
				}
			}
			
			else
				view.promptMsg("Oops!", "You have no permission to do this!", JOptionPane.ERROR_MESSAGE);
		}
	}
	class DenyListener implements ActionListener
	{
		public void actionPerformed(ActionEvent e)
		{
			view.setModeListApprove(model.getApprovalList(view.getUserID()));
		}
	}
	class DeleteAllListener implements ActionListener
	{
		public void actionPerformed(ActionEvent e)
		{
			if (view.getIsLogin() && view.getIsAdmin())
			{
				int confirm = view.promptConfirm("Approve wiki", "Are you sure you want to delete all the wikis?");
				if (confirm == 0)
				{
					//model.approveWiki(view.getCurrWikiID(), view.getCurrAuthor());//This one how to delete all the wikis?*********************************
				}
			}
			
			else
				view.promptMsg("Oops!", "You have no permission to do this!", JOptionPane.ERROR_MESSAGE);
		}
	}
	class IgnoreListener implements ActionListener
	{
		public void actionPerformed(ActionEvent e)
		{
			view.setModeListReported(model.getReportedList(view.getUserID()));
		}
	}
	
	/*
	 * Highlights Listener
	 */
	class HighlightListener implements ActionListener
	{
		public void actionPerformed(ActionEvent e)
		{
			WikiItem temp = (WikiItem) e.getSource();
			view.setModeView(model.viewWiki(temp.getIndex(), view.getUserID()), view.getContentType());
			/*************Added codes***************/
			//System.out.println("Curr User: " + view.getUserID());
		}
	}
	
	public ActionListener getHighlightListener()
	{
		return new HighlightListener();
	}
	
}
